package cn.com.libertymutual.sp.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;

import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sp.bean.TbSpSaleLog;
import cn.com.libertymutual.sp.bean.TbSpShare;
import cn.com.libertymutual.sp.bean.TbSysHotarea;
import cn.com.libertymutual.sp.dao.ShareDao;
import cn.com.libertymutual.sp.dao.SpSaleLogDao;
import cn.com.libertymutual.sp.dao.TbSysHotareaDao;
import cn.com.libertymutual.sp.service.api.ActivityService;
import cn.com.libertymutual.sp.service.api.BranchSetService;
import cn.com.libertymutual.sp.service.api.ShareService;

@Service("shareService")
public class ShareServiceImpl implements ShareService {

	private Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private BranchSetService branchSetService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private TbSysHotareaDao hotareaDao;
	@Autowired
	private ShareDao shareDao;
	@Autowired
	private SpSaleLogDao spSaleLogDao;

	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Modifying(clearAutomatically = true) // @Modifying注解需要使用clearAutomatically=true，同一接口更新后立即查询获得更新后的数据,默认false查询还是更新前的数据
	@Override
	public ServiceResult saveShare(ServiceResult sr, String userCode, String productId, String shareId, String shareType, HttpServletRequest request,
			String agrementNo, String saleCode, String saleName, String channelName, boolean isHotArea, String areaCode, String refUuid) {
		// 日志
		TbSpSaleLog saleLog = new TbSpSaleLog();
		saleLog.setOperation(TbSpSaleLog.UP_SHARE);
		saleLog.setUserCode(userCode);
		saleLog.setMark(TbSpSaleLog.UP_SHARE);
		saleLog.setRequestTime(new Date());
		saleLog.setRequestData("用户编码:" + userCode + ",分享页面：" + productId + "，分享类型：" + shareType + "，" + "<br>agrementNo：" + agrementNo + "，saleCode："
				+ saleCode + "，saleName：" + saleName + "，" + "<br>channelName：" + channelName + "，isHotArea：" + isHotArea + "，" + "<br>areaCode："
				+ areaCode + "，refUuid：" + refUuid + "，shareId：" + shareId);

		List<TbSpShare> tsList = shareDao.findByShareId(shareId);
		if (CollectionUtils.isNotEmpty(tsList)) {
			TbSpShare tsp = tsList.get(0);
			tsp.setLastShareType(productId);

			Integer shareNum = tsp.getShareNum();
			if (null != shareNum) {
				shareNum++;
				tsp.setShareNum(shareNum);
			}

			if (StringUtils.isNotBlank(tsp.getShareType()) && tsp.getShareType().indexOf(shareType) == -1 && tsp.getShareType().length() < 90) {
				tsp.setShareType(tsp.getShareType() + " " + shareType);
			}

			if (StringUtils.isNotBlank(tsp.getProductId()) && tsp.getProductId().indexOf(productId) == -1 && tsp.getProductId().length() < 300) {
				tsp.setProductId(tsp.getProductId() + " " + productId);
			}

			tsp.setUpdateTime(new Date());
			shareDao.save(tsp);

			saleLog.setResponseData(JSON.toJSONString(tsp));
			spSaleLogDao.save(saleLog);
			sr.setSuccess();
			sr.setResult("分享信息更新成功");
		} else {
			TbSpShare addTbSp = new TbSpShare();
			addTbSp.setCreateTime(new Date());
			addTbSp.setProductId(productId);
			addTbSp.setShareType(shareType);
			addTbSp.setSharinChain(0);
			addTbSp.setState(TbSpShare.SHARE_TYPE_NO_VISIT);
			if (StringUtils.isBlank(userCode) && StringUtils.isNotBlank(refUuid)) {
				List<TbSpShare> refList = shareDao.findByShareId(shareId);
				if (refList != null && CollectionUtils.isNotEmpty(tsList) && refList.size() > 0) {
					TbSpShare ref = refList.get(0);
					userCode = ref.getUserCode();
				}
			}

			addTbSp.setUserCode(userCode);

			addTbSp.setShareId(shareId);
			addTbSp.setRefShareId(refUuid);
			addTbSp.setUserCodeChain("");
			if (isHotArea) {
				TbSysHotarea hotArea = hotareaDao.findByAreaCode(areaCode);
				addTbSp.setSaleCode(hotArea.getSaleCode());
				addTbSp.setSaleName(hotArea.getSaleName());
				addTbSp.setAgrementNo(hotArea.getAgreementNo());
				addTbSp.setChannelName(hotArea.getBranchName());
			} else {
				addTbSp.setSaleCode(saleCode);
				addTbSp.setSaleName(saleName);
				addTbSp.setAgrementNo(agrementNo);
				addTbSp.setChannelName(channelName);
			}
			shareDao.save(addTbSp);

			saleLog.setResponseData(JSON.toJSONString(addTbSp));
			spSaleLogDao.save(saleLog);
			sr.setSuccess();
			sr.setResult("分享信息保存成功");
		}

		// String birCode = branchSetService.getUserCodeBranchCode(userCode);
		// if (StringUtils.isBlank(birCode)) {
		// birCode = "5000";
		// }
		// if ("微信-朋友圈".equals(shareType)) {
		// if ("商店".equals(productId) || "软文".equals(productId) ||
		// "产品".equals(productId) || "海报".equals(productId) ||
		// "新春大聚惠".equals(productId)) {
		// sr.setResult(activityService.grantScore(birCode,
		// Constants.EXTENSION_DRAW_ACTIVITY_DO, userCode, null));
		// }
		// }
		return sr;
	}

	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Modifying(clearAutomatically = true) // @Modifying注解需要使用clearAutomatically=true，同一接口更新后立即查询获得更新后的数据,默认false查询还是更新前的数据
	@Override
	public ServiceResult saveActivity(ServiceResult sr, String userCode, String shareType, String productId) {
		log.info("saveActivity 触发朋友圈转发活动 ： {}, {}, {}", userCode, shareType, productId);
		log.info("saveActivity userCode ：" + userCode + "  shareType:" + shareType + "  productId:" + productId);
		String birCode = branchSetService.getUserCodeBranchCode(userCode);
		if (StringUtils.isBlank(birCode)) {
			birCode = "5000";
		}
		if ("微信-朋友圈".equals(shareType)) {
			if ("商店".equals(productId) || "软文".equals(productId) || "产品".equals(productId) || "海报".equals(productId) || "新春大聚惠".equals(productId)) {
				sr.setResult(activityService.grantScore(birCode, Constants.EXTENSION_DRAW_ACTIVITY_DO, userCode, null));
				log.info("触发转发活动结果 ： {}", sr.getResult());
			}
		}
		return sr;
	}

	@Override
	public ServiceResult shareList(String shareId, String userCode, String agrementNo, String startTime, String endTime, Integer pageNumber,
			Integer pageSize) {
		ServiceResult sr = new ServiceResult();
		Sort sort = new Sort(Direction.DESC, "id");
		sr.setResult(shareDao.findAll(new Specification<TbSpShare>() {
			public Predicate toPredicate(Root<TbSpShare> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<Predicate>();
				if (StringUtils.isNotEmpty(shareId)) {
					log.info("-------shareId----:{}", shareId);
					predicate.add(cb.like(root.get("shareId").as(String.class), "%" + shareId + "%"));
				}
				if (StringUtils.isNotEmpty(userCode)) {
					log.info("-------userCode----:{}", userCode);
					predicate.add(cb.like(root.get("userCode").as(String.class), "%" + userCode + "%"));
				}
				if (StringUtils.isNotEmpty(agrementNo)) {
					log.info("-------agrementNo----:{}", agrementNo);
					predicate.add(cb.equal(root.get("agrementNo").as(String.class), agrementNo));
				}
				if (StringUtils.isNotEmpty(startTime)) {
					log.info(startTime);
					predicate.add(cb.greaterThanOrEqualTo(root.get("createTime").as(String.class), startTime));
				}
				if (StringUtils.isNotEmpty(endTime)) {
					log.info(endTime);
					predicate.add(cb.lessThanOrEqualTo(root.get("createTime").as(String.class), endTime));
				}

				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		}, PageRequest.of(pageNumber - 1, pageSize, sort)));
		return sr;
	}

	@Override
	public ServiceResult addShare(TbSpShare tbSpShare) {
		ServiceResult sr = new ServiceResult();
		sr.setResult(shareDao.save(tbSpShare));
		return sr;
	}

	@Override
	public ServiceResult removeShare(Integer id) {
		ServiceResult sr = new ServiceResult();
		shareDao.deleteById(id);
		sr.setSuccess();
		return sr;
	}

}
